<template>
  <div class="home-page" ref="homePage">
    <overlay v-if="showMaskLayer"></overlay>
    <div class="wrapper" v-else ref="wrapperContainer">
      <div class="order-list"
           v-for="(item, index) in orderList"
           :key="index"
           @click="orderDetail(item._id)"
      >
        <div class="user_detail">
          <div class="avatar">
            <img :src="item.avatar" v-if="item.avatar" />
            <div class="svg" v-else>
                  <svg  t="1587545175014" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10677" width="32" height="32">
                      <path d="M0 512a512 512 0 1 0 1024 0 512 512 0 0 0-1024 0z" fill="#7FC2FF" p-id="10678"></path>
                      <path d="M840.594286 850.797714A463.542857 463.542857 0 0 1 511.707429 987.428571 463.542857 463.542857 0 0 1 182.857143 850.797714v-299.264C182.857143 368.128 330.093714 219.428571 511.707429 219.428571c181.650286 0 328.886857 148.699429 328.886857 332.068572 0.731429 173.092571 0.731429 272.859429 0 299.300571z" fill="#EBF9FF" p-id="10679"></path>
                      <path d="M329.142857 457.142857a54.857143 54.857143 0 1 0 109.714286 0 54.857143 54.857143 0 0 0-109.714286 0zM585.142857 457.142857a54.857143 54.857143 0 1 0 109.714286 0 54.857143 54.857143 0 0 0-109.714286 0zM402.285714 585.142857a109.714286 109.714286 0 0 0 219.428572 0" fill="#66B5FF" p-id="10680"></path></svg>
              </div>
          </div>
          <div class="information">
            <span class="nickname">{{ item.nickname }}</span>
            <span class="published">
            {{ item.orderCreateTime | dateformat('YYYY年MM月DD日 HH:mm:ss') }}
          </span>
          </div>
          <div class="order_price">
            <span class="dollar">&yen;</span>
            <span class="price">{{ item.orderPrice }}</span>
          </div>
        </div>
        <div class="describe_img">
          <img :src="item.orderPicture[0].url || item.orderPicture[0]" alt />
        </div>
        <div class="order_address">
          <van-icon name="location" />
          <span>{{ item.orderAddress }}</span>
        </div>
        <div class="order_date">
          <div class="expected">
            <span>{{$t('expectedTime')}}</span>
            <br>
            <span class="attention">{{ item.completionTime }}</span>&nbsp;
            <span class="attention">{{ item.timeFrame }}</span>
          </div>
        </div>
        <div class="describe_text">
          <p>{{ item.orderContent }}</p>
        </div>
      </div>
      <div class="placeholder-element" v-if="emptyElementHeight" :style="{height: emptyElementHeight + 'px'}"></div>
      <div class="empty-element" v-if="errorTag">
        <van-empty>
          <template #image>
            <img src="https://img.yzcdn.cn/vant/empty-image-search.png" alt="">
          </template>
          <template #default>
            <div class="describe">{{$t('orders.indexEmpty')}}</div>
          </template>
        </van-empty>
      </div>
    </div>
  </div>
</template>

<script>
import overlay from 'components/content/overlay/overlay.vue';
import { Icon, Empty } from 'vant';
import { mapState, mapMutations } from 'vuex';

export default {
    name: 'home_index',
    data () {
        return {
            orderList: [], // 订单列表
            orderDataTemp: [], // 订单临时数组
            errorTag: false, // 是否启用错误组件
            emptyElementHeight: 0 // 占位元素高度，默认为0
        };
    },
    components: {
        overlay,
        [Icon.name]: Icon,
        [Empty.name]: Empty
    },
    activated () {
        // 由于首页组件被keep-alive，所以请求订单的钩子变更为activated
        this.requestOrderList();
    },
    computed: {
        ...mapState(['filterOrderData', 'showMaskLayer'])
    },
    methods: {
        requestOrderList () {
            this.orderList.length = 0; // 赋值数据之前清空数组
            this.orderDataTemp.length = 0; // 赋值数据之前清空数组
            this.resetStatus({ state: 'showMaskLayer', status: true }); // 是否显示遮罩层
            const orderPromise = this.$api.orderApi.orderList();

            orderPromise.then(result => {
                if (!result.data.length) {
                    this.errorTag = true;
                    const error = this.$t('orders.indexEmpty');
                    Promise.reject(error);
                }
                return result.data;
            }).then(result => {
                this.orderDataTemp = result;
                this.combine(result).then(result => {
                    this.combineUserinfo(result);
                });
            }).catch(error => {
                console.log(error);
                this.$util.failToast(error.message);
                this.resetStatus({ state: 'showMaskLayer', status: false }); // 关闭遮罩层
            });
        },
        orderDetail (orderId) {
            this.$router.push('/detail/' + orderId);
        },
        async combine (res) {
            const userInfoArray = [];
            const saveLength = res.length;
            for (let index = 0; index < saveLength; index++) {
                userInfoArray.push(
                    await this.$api.userApi // await是将异步任务处理成同步任务 这里是获取用户信息完毕之后再返回
                        .getUserInfo({ id: res[index].orderByCreateID })
                        .then(res => {
                            const { avatar, nickname, _id } = res.data;
                            return { avatar, nickname, _id };
                        })
                        .catch(err => console.log(err))
                );
            }
            return userInfoArray;
        },
        combineUserinfo (res) {
            this.resetStatus({ state: 'showMaskLayer', status: false });
            const dataLength = res.length;
            for (let index = 0; index < dataLength; index++) {
                if (res[index]._id === this.orderDataTemp[index].orderByCreateID) {
                    this.orderList.push(Object.assign(this.orderDataTemp[index], {
                        avatar: res[index].avatar,
                        nickname: res[index].nickname
                    }));
                }
            }
            this.$nextTick(() => {
                const pageHeight = this.$util.ScreenCanUseHeight(this.$store.state.tabbarHeight);
                const resetHeight = this.$refs.wrapperContainer.clientHeight - pageHeight;
                if (resetHeight > 0) {
                    this.emptyElementHeight = this.$store.state.tabbarHeight;
                }
            });
        },
        ...mapMutations(['resetStatus'])
    },
    watch: {
        filterOrderData: function (value) {
            this.errorTag = false;
            this.orderList.splice(0, this.orderList.length);
            this.orderDataTemp.splice(0, this.orderDataTemp.length);
            if (!value.length) {
                this.errorTag = true;
            } else {
                this.orderDataTemp = value;
                this.combine(value).then(res => this.combineUserinfo(res));
            }
        }
    }
};
</script>

<style scoped lang="less" src="./less/home-index.less"></style>
